﻿using Pay.DTO;
using Pay.IService;
using Pay.Data;
using Pay.Core;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Pay.Service.Cache;

namespace Pay.Service {
    public class TokenBillService : ServiceBase, ITokenBillService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private ITokenUpGradeService _iTokenUpGradeService;
        private ITokenStatisticsService _iTokenStatisticsService;
        private IMerchantReceivablesService _iMerchantReceivablesService;
        private IMessagePushService _iMessagePushService;
        private ISettingService _iSettingService;
        private ITokenGradeService _iTokenGradeService;
        private IMerchantService _merchantService;
        private readonly static object ConfirmUserBilllock = new object();
        private readonly static object SysConfirmBilllock = new object();
        public TokenBillService(IUnitOfWork iUnitOfWork, ITokenUpGradeService iTokenUpGradeService, IMessagePushService iMessagePushService,
                                ITokenStatisticsService iTokenStatisticsService, IMerchantReceivablesService iMerchantReceivablesService,
                                ISettingService iSettingService, ITokenGradeService iTokenGradeService, IMerchantService merchantService) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
            _iTokenUpGradeService = iTokenUpGradeService;
            _iTokenStatisticsService = iTokenStatisticsService;
            _iMerchantReceivablesService = iMerchantReceivablesService;
            _iMessagePushService = iMessagePushService;
            _iSettingService = iSettingService;
            _iTokenGradeService = iTokenGradeService;
            _merchantService = merchantService;
        }

        public bool CreateTokenBill(UserAudit audit, List<bind_merchant_item> binds) {
            long timestamp = DateTime.Now.ToUnix();
            var tokenAudit = context.TokenUpGrade.FirstOrDefault(c => c.Id == audit.id);
            var user_type = audit.user_type.HasValue ? audit.user_type.Value : tokenAudit.GradeId;
            if (tokenAudit.EUpGradeAudit != EUpGradeAudit.PendingAudit)
                throw new ServerErrorException("当前状态不是待审核状态，无法操作！");
            tokenAudit.EUpGradeAudit = TO.EUpGradeAudit.Auditing;
            tokenAudit.GradeId = user_type;
            if (user_type == UserType.tokenNodeMall) {
                var statistics = _iTokenStatisticsService.CreateStatistics(tokenAudit.CityCompanyMerchantId);
                if (statistics.TotalSurplusOpenMaker < 1)
                    throw new ServerErrorException("您的节点商城开通数量不足无法开通，请您前往'我的业务员'购买。");
                statistics.TotalSurplusOpenMaker -= 1;
            }
            var tokenBill = AddTokenBill(tokenAudit, binds);
            var details = new List<TokenBillDetail>();
            var tokens = new List<TokenStatistics>();
            foreach (var bind in binds) {
                var merchant = _merchantService.Get(bind.merchant_no);
                var statistics = context.TokenStatistics.FirstOrDefault(c => c.MerchantId == merchant.id);
                if (statistics == null) {
                    statistics = new TokenStatistics {
                        MerchantId = merchant.id,
                        UnConfirmProfit = bind.amount,
                        CreateTime = timestamp
                    };
                    tokens.Add(statistics);
                } else {
                    statistics.UnConfirmProfit += bind.amount;
                }
                context.TokenStatistics.AddRange(tokens);
                var apply_merchant = _iMerchantReceivablesService.GetReceivablesInfo(merchant.id);
                var model = new TokenBillDetail {
                    TokenBill = tokenBill,
                    MerchantId = merchant.id,
                    CreateTime = timestamp,
                    UpdateTime = timestamp,
                    Commission = bind.amount,
                    InviteMerchantId = tokenAudit.MerchantId,
                    Proportion = bind.percent,
                    UserType = user_type,
                    ReceivablesInfo = (apply_merchant != null ? apply_merchant.ToJson() : "")
                };
                details.Add(model);
            }
            context.TokenBillDetail.AddRange(details);
            var msg_setting = _iSettingService.GetTokenSetting().msg;
            var msg = msg_setting.FirstOrDefault(s => s.code == "bill_confirming");
            MessagePush message = new MessagePush() {
                Title = msg.name,
                Content = msg.content,
                CreateTime = DateTime.Now.ToUnix(),
                MerchantId = tokenAudit.CityCompanyMerchantId,
                ShortContent = msg.content,
                Type = MsgType.Marketing,
                Ext = "{}",
                IsRead = false,
                Filter = false
            };
            context.MessagePushs.Add(message);
            var result = _iUnitOfWork.Commit() > 0;
            return result;
        }
        /// <summary>
        /// 生成分销、业绩收益账单
        /// </summary>
        /// <param name="merchant_id"></param>
        /// <param name="binds"></param>
        /// <param name="pay_id"></param>
        /// <param name="busType"></param>
        public void CreateTokenBill(long merchant_id, List<bind_merchant_item> binds, long pay_id = 0, BusType busType = BusType.None) {
            var timestamp = DateTime.Now.ToUnix();
            TokenBill tokenBill = null;
            if (busType == BusType.UpGrade)
                tokenBill = AddTokenBill(merchant_id, binds);
            else if (busType == BusType.Mall)
                tokenBill = AddTokenMallBill(binds);
            var details = new List<TokenBillDetail>();
            var tokens = new List<TokenStatistics>();
            foreach (var bind in binds) {
                var merchant = _merchantService.Get(bind.merchant_no);
                var statistics = context.TokenStatistics.FirstOrDefault(c => c.MerchantId == merchant.id);
                if (statistics == null) {
                    statistics = new TokenStatistics {
                        MerchantId = merchant.id,
                        Deposit = 0,
                        CreateTime = timestamp,
                        ConfirmProfit = bind.amount,
                        BusDeposit = 0,
                        BusDeposited = 0,
                        BusDepositing = 0,
                        FrozenBusProfit = 0,
                        Deposited = 0,
                        Depositing = 0
                    };
                    tokens.Add(statistics);
                } else {
                    statistics.ConfirmProfit += bind.amount;
                }
                if (bind.is_bus) {
                    statistics.FrozenBusProfit = (statistics.FrozenBusProfit ?? 0) + bind.amount;
                } else {
                    statistics.FrozenProfit += bind.amount;
                }
                var user = _merchantService.Get(merchant_id);
                context.TokenStatistics.AddRange(tokens);
                var model = new TokenBillDetail {
                    TokenBill = tokenBill,
                    MerchantId = merchant.id,
                    CreateTime = timestamp,
                    UpdateTime = timestamp,
                    Commission = bind.amount,
                    InviteMerchantId = (user == null ? 0 : user.parent_id),
                    Proportion = bind.percent,
                    UserType = UserType.tokenMaker,
                    IsComfirm = true,
                    IsBus = bind.is_bus,
                    BusType = busType,
                    Type = 0,
                    PayId = pay_id,
                    ReceivablesInfo = "",
                    BillStatus = BillStatus.Proceed,
                    BillType = (busType == BusType.UpGrade ? TokenBillType.MarkBill : TokenBillType.DistributionBill)
                };
                details.Add(model);
            }
            context.TokenBillDetail.AddRange(details);
        }
        /// <summary>
        /// 398商品账单解冻
        /// </summary>
        /// <param name="pay_id"></param>
        public void UpAccountDeblock(long pay_id) {
            var details = context.TokenBillDetail.Where(c => c.PayId == pay_id).ToList();
            details.DataForEach(detail => {
                detail.Type = 1;
                if (detail.BillStatus == BillStatus.Finish || detail.BillStatus == BillStatus.Cancel)
                    return;
                detail.BillStatus = BillStatus.Finish;
                bool has_account = context.TokenStatistics.Any(c => c.MerchantId == detail.MerchantId);
                if (has_account) {
                    var account = context.TokenStatistics.FirstOrDefault(c => c.MerchantId == detail.MerchantId);
                    if (detail.BusType == BusType.UpGrade) {
                        //业绩
                        account.BusDeposit = (account.BusDeposit ?? 0) + detail.Commission;
                        account.FrozenBusProfit = (account.FrozenBusProfit ?? 0) - detail.Commission;
                    }
                }
            });
            //货款
            var billDetail = context.BillDetails.FirstOrDefault(c => c.PayId == pay_id && c.BillType == BillType.Mall);
            if (billDetail != null) {
                if (billDetail.Status == BillStatus.Finish || billDetail.Status == BillStatus.Cancel)
                    return;
                billDetail.Status = BillStatus.Finish;
                billDetail.Bill.GoodsUnconfirmed -= billDetail.Amount;
                billDetail.Bill.GoodsDeposit += billDetail.Amount;
            }
        }
        /// <summary>
        /// 业绩解冻
        /// </summary>
        /// <param name="pay_id"></param>
        public void MallAccountDeBlock(long pay_id) {
            var details = context.TokenBillDetail.Where(c => c.PayId == pay_id).ToList();
            details.DataForEach(detail => {
                detail.Type = 1;
                if (detail.BillStatus == BillStatus.Finish || detail.BillStatus == BillStatus.Cancel)
                    return;
                detail.BillStatus = BillStatus.Finish;
                bool has_account = context.TokenStatistics.Any(c => c.MerchantId == detail.MerchantId);
                if (has_account) {
                    var account = context.TokenStatistics.FirstOrDefault(c => c.MerchantId == detail.MerchantId);
                    if (detail.BusType == BusType.Mall) {
                        //业绩
                        account.BusDeposit = (account.BusDeposit ?? 0) + detail.Commission;
                        account.FrozenBusProfit = (account.FrozenBusProfit ?? 0) - detail.Commission;
                    }
                }
            });
        }
        /// <summary>
        /// 商城退款业绩收益退回
        /// </summary>
        /// <param name="pay_id"></param>
        public void MallRefundAccount(long pay_id) {
            var details = context.TokenBillDetail.Where(c => c.PayId == pay_id).ToList();
            details.DataForEach(detail => {
                if (detail.BillStatus == BillStatus.Cancel) return;
                detail.Remark = "退款";
                detail.BillStatus = BillStatus.Cancel;
                var statistics = context.TokenStatistics.FirstOrDefault(c => c.MerchantId == detail.MerchantId);
                if (statistics.FrozenBusProfit > 0)
                    statistics.FrozenBusProfit = (statistics.FrozenBusProfit ?? 0) - detail.Commission;
            });
        }

        private TokenBill AddTokenBill(TokenUpGrade model, List<bind_merchant_item> binds) {
            var parent = _merchantService.Get(model.ApplyMerchantId);
            var parents = _merchantService.GetParents(parent.id).Select(c => c.id.ToString());
            var path = parents.Aggregate((x, y) => x + "-" + y);
            var tokenBill = new TokenBill {
                CityCompanyMerchantId = model.CityCompanyMerchantId,
                ApplyMerchantId = model.ApplyMerchantId,
                MerchantId = model.MerchantId,
                Profit = binds.ToJson(),
                EMaidStatus = TO.EMaidStatus.Launch,
                CreateTime = DateTime.Now.ToUnix(),
                UserType = model.GradeId,
                InviteMerchantPath = path,
                TotalCommission = model.Amount
            };
            context.TokenBill.Add(tokenBill);
            return tokenBill;
        }

        private TokenBill AddTokenBill(long merchant_id, List<bind_merchant_item> binds) {
            var merchant = _merchantService.Get(merchant_id);
            var parents = _merchantService.GetParents(merchant_id).Select(c => c.id.ToString());
            var path = parents.Aggregate((x, y) => x + "-" + y);
            var tokenBill = new TokenBill {
                CityCompanyMerchantId = 1,
                ApplyMerchantId = merchant_id,
                MerchantId = merchant.parent_id,
                Profit = binds.ToJson(),
                EMaidStatus = EMaidStatus.Completed,
                CreateTime = DateTime.Now.ToUnix(),
                UserType = UserType.tokenMaker,
                InviteMerchantPath = path,
                TotalCommission = 0
            };
            context.TokenBill.Add(tokenBill);
            return tokenBill;
        }

        private TokenBill AddTokenMallBill(List<bind_merchant_item> binds) {
            var tokenBill = new TokenBill {
                CityCompanyMerchantId = 1,
                ApplyMerchantId = 0,
                MerchantId = 0,
                Profit = binds.ToJson(),
                EMaidStatus = EMaidStatus.Completed,
                CreateTime = DateTime.Now.ToUnix(),
                UserType = UserType.None,
                InviteMerchantPath = "",
                TotalCommission = 0
            };
            context.TokenBill.Add(tokenBill);
            return tokenBill;
        }
        /// <summary>
        /// 发起分佣 （分佣列表）
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<token_bill_dto> Gets(TokenBillQuery query) {
            var filter = PredicateBuilder.True<TokenBill>();
            if (query.merchant_id.GetValueOrDefault(0) > 0)
                filter = filter.And(c => c.MerchantId == query.merchant_id);
            if (query.city_merchant_id.GetValueOrDefault(0) > 0) {
                filter = filter.And(c => c.CityCompanyMerchantId == query.city_merchant_id);
            }
            if (!string.IsNullOrEmpty(query.name))
                filter = filter.And(c => c.CityCompanyMerchant.Name.Contains(query.name) || c.CityCompanyMerchant.Mobile.Contains(query.name) || c.Merchant.Mobile.Contains(query.name));
            if (query.start_time.HasValue) {
                long startTime = query.start_time.Value.ToUnix();
                filter = filter.And(c => c.CreateTime >= startTime);
            }
            if (query.end_time.HasValue) {
                long endTime = query.end_time.Value.AddDays(1).ToUnix();
                filter = filter.And(c => c.CreateTime <= endTime);
            }
            if (query.e_maid_aduit.HasValue) {
                filter = filter.And(c => c.EMaidStatus == (EMaidStatus)query.e_maid_aduit.Value);
            }

            return context.TokenBill.FromCachePaged<TokenBill, token_bill_dto>(query.page, query.size, filter, orderBy => orderBy.OrderBy(c => c.EMaidStatus).ThenByDescending(s => s.CreateTime));
        }
        /// <summary>
        /// 单个账单分佣明细
        /// </summary>
        /// <param name="id">账单id</param>
        /// <returns></returns>
        public List<token_bill_detial_dto> getBillDetails(long id) {
            var list = context.TokenBillDetail.Where(s => s.TokenBillId == id).ToList().ToDtoList<token_bill_detial_dto>();
            return list;
        }

        private static readonly object objkey = new object();


        /// <summary>
        /// 确认分佣
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool ConfirmBillMaid(confirm_bill_maid_model model) {
            lock (objkey) {
                var merchant = _merchantService.Get(model.merchant_id);
                if (merchant.usertype != UserType.tokenCityAgent) {
                    throw new ServerErrorException("你无权限操作");
                }
                var bill = context.TokenBill.FindById(model.bill_id);
                if (bill.EMaidStatus != EMaidStatus.Launch) { throw new ServerErrorException("待发起状态才能分佣"); }
                var list = context.TokenBillDetail.Where(s => s.TokenBillId == model.bill_id).ToList();
                List<MessagePush> messages = new List<MessagePush>();
                var msg_setting = _iSettingService.GetTokenSetting().msg;
                var msg = msg_setting.FirstOrDefault(s => s.code == "bill_unconfirm");
                confirm_user_bill_model confirm_model = new confirm_user_bill_model();
                foreach (var item in list) {
                    var billDeatil = model.bill_details.FirstOrDefault(s => s.bill_deatil_id == item.Id);
                    if (item.MerchantId == model.merchant_id) {
                        confirm_model.user_id = model.merchant_id;
                        confirm_model.bill_deatil_id = item.Id;
                        confirm_model.comfirm_transfer_voucher = string.Empty;

                    } else {
                        if (billDeatil == null || (billDeatil != null && string.IsNullOrEmpty(billDeatil.transfer_voucher))) { throw new ServerErrorException("请上传转账凭证"); }
                        item.TransferVoucher = billDeatil.transfer_voucher;
                    }

                    MessagePush message = new MessagePush() {
                        Title = msg.name,
                        Content = msg.content,
                        CreateTime = DateTime.Now.ToUnix(),
                        MerchantId = item.MerchantId,
                        ShortContent = msg.content,
                        Type = MsgType.Marketing,
                        Ext = "{}",
                        IsRead = false,
                        Filter = false
                    };
                    messages.Add(message);
                }
                bill.EMaidStatus = EMaidStatus.Maiding;
                bill.LaunchTime = DateTime.Now.ToUnix();
                context.MessagePushs.AddRange(messages);
                using (var trans = context.Database.BeginTransaction()) {
                    try {
                        int r = _iUnitOfWork.Commit();
                        bool c = true;
                        if (confirm_model.user_id > 0) { c = ConfirmUserBill(confirm_model); }
                        if (r > 0 && c == true) {
                            trans.Commit();
                            return true;
                        } else {
                            trans.Rollback();
                            return false;
                        }
                    } catch (Exception ex) {
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }
        /// <summary>
        /// 收益列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<token_bill_detial_dto> Gets(TokenBillDetailQuery query) {
            var filter = PredicateBuilder.True<TokenBillDetail>();

            filter = filter.And(c => c.MerchantId == query.merchant_id);

            return context.TokenBillDetail.FromCachePaged<TokenBillDetail, token_bill_detial_dto>(query.page, query.size, filter, orderBy => orderBy.OrderBy(c => c.IsComfirm).ThenByDescending(c => c.CreateTime));
        }
        /// <summary>
        /// 账单明细详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public token_bill_detial_dto GetBillDetail(long id) {
            return context.TokenBillDetail.FindById(id).ToDtoObject<token_bill_detial_dto>();
        }
        /// <summary>
        /// 账单总账详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public token_bill_dto GetBill(long id) {
            return context.TokenBill.FindById(id).ToDtoObject<token_bill_dto>();
        }
        /// <summary>
        ///确认收益
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool ConfirmUserBill(confirm_user_bill_model model) {
            lock (ConfirmUserBilllock) {
                var billDetail = context.TokenBillDetail.FirstOrDefault(s => s.Id == model.bill_deatil_id && s.MerchantId == model.user_id);
                if (billDetail == null) throw new ServerErrorException("不存在该数据");
                if (billDetail.IsComfirm) throw new ServerErrorException("分佣已确认");
                if (billDetail.TokenBill.EMaidStatus != EMaidStatus.Maiding) { throw new ServerErrorException("账单状态只有在分佣中才能确认收益"); }
                int count = context.TokenBillDetail.Where(s => s.TokenBillId == billDetail.TokenBillId && s.IsComfirm == false).Count();
                billDetail.ComfirmTransferVoucher = model.comfirm_transfer_voucher;
                billDetail.IsComfirm = true;
                var usercommion = context.TokenStatistics.FirstOrDefault(s => s.MerchantId == model.user_id);
                usercommion.UnConfirmProfit -= billDetail.Commission;
                usercommion.ConfirmProfit += billDetail.Commission;
                var tokenUpGrade = context.TokenUpGrade.FirstOrDefault(s => s.ApplyMerchantId == billDetail.TokenBill.ApplyMerchantId && s.GradeId == billDetail.UserType);
                if (tokenUpGrade == null) { throw new ServerErrorException("申请记录不存在"); }
                //var merchant = _merchantService.Get(billDetail.TokenBill.ApplyMerchantId);
                var merchant = context.Merchants.FindById(billDetail.TokenBill.ApplyMerchantId);
                //确认收益人是邀请人&&申请角色为创客
                if (model.user_id == tokenUpGrade.MerchantId && billDetail.UserType == UserType.tokenMaker) {
                    merchant.UserType = billDetail.TokenBill.UserType;
                    tokenUpGrade.EUpGradeAudit = EUpGradeAudit.Audited;
                    tokenUpGrade.AuditTime = DateTime.Now.ToUnix();
                } //其他人确认收益完用户才升级
                if (count == 1) {
                    merchant.UserType = billDetail.TokenBill.UserType;
                    billDetail.TokenBill.EMaidStatus = EMaidStatus.Completed;
                    tokenUpGrade.EUpGradeAudit = EUpGradeAudit.Audited;
                    tokenUpGrade.AuditTime = DateTime.Now.ToUnix();
                }
                if (tokenUpGrade.EUpGradeAudit == EUpGradeAudit.Audited) {
                    var msg_setting = _iSettingService.GetTokenSetting().msg;
                    var msg = msg_setting.FirstOrDefault(s => s.code == "user_type_change");
                    MessagePush message = new MessagePush() {
                        Title = msg.name,
                        Content = msg.content,
                        CreateTime = DateTime.Now.ToUnix(),
                        MerchantId = merchant.Id,
                        ShortContent = msg.content,
                        Type = MsgType.Marketing,
                        Ext = "{}",
                        IsRead = false,
                        Filter = false
                    };
                    context.MessagePushs.Add(message);
                }
                int r = _iUnitOfWork.Commit("Merchant" + merchant.Id);
                return r > 0;
            }
        }
        /// <summary>
        /// 系统确认收益
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool SysConfirmUserBill(long id, long UserId) {
            lock (ConfirmUserBilllock) {
                var billDetail = context.TokenBillDetail.FirstOrDefault(s => s.Id == id);
                if (billDetail == null) throw new ServerErrorException("不存在该数据");
                if (billDetail.IsComfirm) throw new ServerErrorException("分佣已确认");
                if (billDetail.TokenBill.EMaidStatus != EMaidStatus.Maiding) { throw new ServerErrorException("账单状态只有在分佣中才能确认收益"); }
                int count = context.TokenBillDetail.Where(s => s.TokenBillId == billDetail.TokenBillId && s.IsComfirm == false).Count();
                billDetail.ComfirmTransferVoucher = string.Empty;
                billDetail.IsComfirm = true;
                var usercommion = context.TokenStatistics.FirstOrDefault(s => s.MerchantId == billDetail.MerchantId);
                usercommion.UnConfirmProfit -= billDetail.Commission;
                usercommion.ConfirmProfit += billDetail.Commission;
                var tokenUpGrade = context.TokenUpGrade.FirstOrDefault(s => s.ApplyMerchantId == billDetail.TokenBill.ApplyMerchantId && s.GradeId == billDetail.UserType);
                if (tokenUpGrade == null) { throw new ServerErrorException("申请记录不存在"); }
                var merchant = context.Merchants.FindById(billDetail.TokenBill.ApplyMerchantId);
                //var merchant = _merchantService.Get(billDetail.TokenBill.ApplyMerchantId);
                //确认收益人是邀请人&&申请角色为创客
                if (billDetail.MerchantId == tokenUpGrade.MerchantId && billDetail.UserType == UserType.tokenMaker) {
                    merchant.UserType = billDetail.TokenBill.UserType;
                    tokenUpGrade.EUpGradeAudit = EUpGradeAudit.Audited;
                    tokenUpGrade.AuditTime = DateTime.Now.ToUnix();
                }  //其他人确认收益完用户才升级
                if (count == 1) {
                    merchant.UserType = billDetail.TokenBill.UserType;
                    billDetail.TokenBill.EMaidStatus = EMaidStatus.Completed;
                    tokenUpGrade.EUpGradeAudit = EUpGradeAudit.Audited;
                    tokenUpGrade.AuditTime = DateTime.Now.ToUnix();
                }
                if (tokenUpGrade.EUpGradeAudit == EUpGradeAudit.Audited) {
                    var msg_setting = _iSettingService.GetTokenSetting().msg;
                    var msg = msg_setting.FirstOrDefault(s => s.code == "user_type_change");
                    MessagePush message = new MessagePush() {
                        Title = msg.name,
                        Content = msg.content,
                        CreateTime = DateTime.Now.ToUnix(),
                        MerchantId = merchant.Id,
                        ShortContent = msg.content,
                        Type = MsgType.Marketing,
                        Ext = "{}",
                        IsRead = false,
                        Filter = false
                    };
                    context.MessagePushs.Add(message);
                }
                var manage = context.Manages.FindById(UserId);
                billDetail.Remark = string.Format("系统审核***操作人：{0}***** 操作人手机号：{1}**** 操作人手机号：{2}", manage.Nick, manage.Mobile, manage.Id);
                int r = _iUnitOfWork.Commit("Merchant" + merchant.Id);
                return r > 0;
            }

        }
        /// <summary>
        /// token 钱包课程收益
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<token_wallet_bill_detail_dto> GetWalletBillDetails(WalletQuery query) {
            var filter = PredicateBuilder.True<TokenBillDetail>();
            filter = filter.And(c => (c.MerchantId == query.merchant_id && c.Remark == "在线购买课程") || (c.MerchantId == query.merchant_id && c.IsBus == false && c.BusType == BusType.UpGrade));
            return context.TokenBillDetail.FromCachePaged<TokenBillDetail, token_wallet_bill_detail_dto>(query.page, query.size, filter, orderBy => orderBy.OrderBy(c => c.IsComfirm).ThenByDescending(c => c.CreateTime));
        }
    }
}
